﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Service;

namespace ECommerce.Controls
{
	public partial class SiteNews : BaseUserControl
	{
		private INewsService _NewsService;

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindNews();

			this.LSiteNewsTitle.Text = GetLocalResourceString("SiteNews.Title");
		}

		protected void RepeaterNews_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if(e.Item.DataItem != null)
			{
				HyperLink hl = (HyperLink)e.Item.FindControl("HyperLinkNewsItem");
				var theNews = (Data.Entity.News)e.Item.DataItem;

				hl.Text = theNews.Title;
				hl.NavigateUrl = "~/News.aspx?newsid=" + theNews.NewsID.ToString();
			}
		}

		private void BindNews()
		{
			if (SiteContext.Current != null || SiteContext.Current.WorkingLanguage != null)
			{
				int languageID = SiteContext.Current.WorkingLanguage.LanguageId;

				if (_NewsService == null)
				{
					_NewsService = new NewsService();
				}

				var allNews = _NewsService.GetNewsByLanguage(languageID);

				if (allNews != null)
				{
					var news = allNews.Take(8);

					RepeaterNews.DataSource = news;
					RepeaterNews.DataBind();
				}
				else
				{
					RepeaterNews.DataSource = null;
					RepeaterNews.DataBind();
				}
			}
		}
	}
}